import numpy as np
import tensorflow as tf
import cv2
import os
import tempfile
import logging
import re

def break_one_video( video_path , export_path ):
    cap = cv2.VideoCapture( video_path )

    if not os.path.exists( export_path ):
        os.mkdir( export_path )
    
    file_list = os.listdir( export_path )
    logging.warning( "the exporting directory has %d files " , len(file_list) )

    while( True ):
        ret, frame = cap.read()
        if ret == True:
            frame_name = tempfile.mktemp( suffix='.jpg' , dir = export_path )
            cv2.imwrite( frame_name , frame )
        else:
            break

    cap.release()

def find_all_mov( dir_path , pattern ):
    # find all files whose suffix is .mov recursively while match the pattern
    file_list = os.listdir( dir_path )
   
    mov_list = []
    for f in file_list:
        file_abspath = os.path.join( dir_path , f )
        if os.path.isfile( file_abspath ):
            if re.match( pattern , f ):
                mov_list.append( file_abspath )
        elif os.path.isdir( file_abspath ):
            mov_list.extend( find_all_mov( file_abspath , pattern ) )
        else:
            pass

    return mov_list

if __name__ == "__main__":
    #mov_list = find_all_mov( "/home/jh/working_data/replayattack/replayattack/train" , r'client.*mov' )

    #for mov in mov_list:
    #    print( mov )

    client_mov_list = find_all_mov( "/home/jh/working_data/replayattack/replayattack/train" , r'client.*mov' )
    attack_mov_list = find_all_mov( "/home/jh/working_data/replayattack/replayattack/train" , r'attack.*mov' )

    for f in client_mov_list:
        break_one_video( f , "/home/jh/working_pros/binary_classifier/replay_attack/pos" )

    for f in attack_mov_list:
        break_one_video( f , "/home/jh/working_pros/binary_classifier/replay_attack/neg" )
